package com.yuyou.train.user.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yuyou.train.service.api.admin.service.CommDataConfigAPI;
import com.yuyou.train.service.api.lesson.dto.ResourceDetailDTO;
import com.yuyou.train.service.api.lesson.dto.UserLessonTreeDTO;
import com.yuyou.train.service.api.lesson.entity.Lesson;
import com.yuyou.train.service.api.lesson.entity.LessonClassUserRelation;
import com.yuyou.train.service.api.lesson.entity.LessonResourceRuleFrame;
import com.yuyou.train.service.api.lesson.entity.ResourceExam;
import com.yuyou.train.service.api.lesson.entity.ResourceExamItem;
import com.yuyou.train.service.api.lesson.entity.ResourceQuestion;
import com.yuyou.train.service.api.lesson.entity.Rule;
import com.yuyou.train.service.api.lesson.service.ExamAPI;
import com.yuyou.train.service.api.lesson.service.LessonAPI;
import com.yuyou.train.service.api.lesson.service.QuestionAPI;
import com.yuyou.train.service.api.lesson.service.ResourceAPI;
import com.yuyou.train.service.api.lesson.service.RuleAPI;
import com.yuyou.train.service.api.user.dto.UserLessonCommentDTO;
import com.yuyou.train.service.api.user.entity.User;
import com.yuyou.train.service.api.user.entity.UserComment;
import com.yuyou.train.service.api.user.entity.UserHw;
import com.yuyou.train.service.api.user.entity.UserHwTeacher;
import com.yuyou.train.service.api.user.entity.UserLessonProgress;
import com.yuyou.train.service.api.user.entity.UserMedalItem;
import com.yuyou.train.service.api.user.entity.UserPraise;
import com.yuyou.train.service.api.user.entity.UserThoughts;
import com.yuyou.train.user.service.IUserCommentService;
import com.yuyou.train.user.service.IUserDataConfigService;
import com.yuyou.train.user.service.IUserHwBeService;
import com.yuyou.train.user.service.IUserHwPraiseService;
import com.yuyou.train.user.service.IUserHwService;
import com.yuyou.train.user.service.IUserHwTeacherService;
import com.yuyou.train.user.service.IUserLessonProgressBehaService;
import com.yuyou.train.user.service.IUserLessonProgressService;
import com.yuyou.train.user.service.IUserLookService;
import com.yuyou.train.user.service.IUserPointsService;
import com.yuyou.train.user.service.IUserPraiseService;
import com.yuyou.train.user.service.IUserService;
import com.yuyou.train.user.service.IUserThoughtsService;
import com.yuyou.train.user.vo.req.ReqBehavior;
import com.yuyou.train.user.vo.req.ReqBehaviorEnd;
import com.yuyou.train.user.vo.resp.RespGetLessonContent;
import com.yuyou.train.user.vo.resp.RespGetLessonEnding;
import com.yuyou.train.user.vo.resp.RespGetLessonEndingMark;
import com.yuyou.train.user.vo.resp.RespGetLessonExam;
import com.yuyou.train.user.vo.resp.RespGetLessonExamAns;
import com.yuyou.train.user.vo.resp.RespGetLessonHwComment;
import com.yuyou.train.user.vo.resp.RespGetLessonHwCommit;
import com.yuyou.train.user.vo.resp.RespGetLessonResource;
import com.yuyou.train.user.vo.resp.RespGetLessonTeacher;
import com.yuyou.train.user.vo.resp.RespGetLessonThought;
import com.yuyou.train.user.vo.resp.RespGetLessonUserInfo;
import com.yuyou.train.user.vo.resp.RespGetLessonVideo;
import com.yuyou.train.util.bean.ResBoolSimpleInfo;
import com.yuyou.train.util.constant.lesson.LessonCons;
import com.yuyou.train.util.constant.user.UserLessonProgressCons;
import com.yuyou.train.util.enums.CommEnums;
import com.yuyou.train.util.enums.lesson.LessonEnums;
import com.yuyou.train.util.enums.user.UserCommentEnums;
import com.yuyou.train.util.enums.user.UserEnums;
import com.yuyou.train.util.enums.user.UserHwEnums;
import com.yuyou.train.util.enums.user.UserLessonProgressEnums;
import com.yuyou.train.util.enums.user.UserPointsEnums;
import com.yuyou.train.util.enums.user.UserPraiseEnums;
import com.yuyou.train.util.message.CommMess;
import com.yuyou.train.util.message.user.UserLessonProMess;
import com.yuyou.train.util.message.user.UserPointsMess;
import com.yuyou.train.util.tool.DefindBeanUtils;

@Service
public class UserLessonProgressBehaServiceImpl implements IUserLessonProgressBehaService{

	@Autowired
	IUserLessonProgressService userLessonProgressService;

	@Autowired
	public IUserService userService;
	
	@Autowired
	public IUserDataConfigService userDataConfigService;
	
	@Autowired
	public IUserHwService userHwService;
	
	@Autowired
	public IUserHwPraiseService userHwPraiseService;
	
	@Autowired
	public IUserHwBeService userHwBeService;
	
	@Autowired
	public IUserThoughtsService userThoughtsService;
		
	@Autowired
	public IUserPointsService userPointsService;
	
	@Autowired
	public CommDataConfigAPI commDataConfigAPI;
	
	@Autowired
	public RuleAPI ruleAPI;
	
	@Autowired
	public ResourceAPI resourceAPI;
	
	@Autowired
	public LessonAPI lessonAPI;
	
	@Autowired
	public QuestionAPI questionAPI;
	
	@Autowired
	public ExamAPI examAPI;
	
	@Autowired
	public IUserPraiseService userPraiseService;
	
	@Autowired
	public IUserCommentService userCommentService;
	
	@Autowired
	public IUserHwTeacherService userHwTeacherService;
	
	@Autowired
	public IUserLessonProgressBehaService userLesProBehService;
	
	@Autowired
	public IUserLookService userLookService;
	
	@Override
	public ResBoolSimpleInfo<String> addLessonPoints(String userId,Lesson lesson) {	
		if(lesson !=null && lesson.getScore()!=null &&lesson.getScore()>0){
			userPointsService.addPoints(userId,UserPointsEnums.action.add.getValue(),String.format(UserPointsMess.ADD_LESSON_POINT, lesson.getName(),lesson.getScore()),lesson.getScore());	
		}
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	

	@Override
	public ResBoolSimpleInfo<String> addMedalPoints(String userId,
			UserMedalItem userMedalItem) {	
		if(userMedalItem !=null && userMedalItem.getScore()!=null &&userMedalItem.getScore()>0){
			userPointsService.addPoints(userId, UserPointsEnums.action.add.getValue(),String.format(UserPointsMess.ADD_MEDAL_POINT, userMedalItem.getName(),userMedalItem.getScore()), userMedalItem.getScore());
		}
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	
	

	@Override
	public ResBoolSimpleInfo<String> solveEnd(User user,UserLessonProgress currProgress,ReqBehavior reqBehavior) throws Exception{
		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
		
		if(!user.getType().equals(UserEnums.type.student.getValue())){
			res.setSuccess(false);
			res.setMessage(CommMess.ERR_POWER);
			return res;
		}
		
		ResBoolSimpleInfo<String> valRes=ReqBehaviorEnd.validate(reqBehavior.getEnd());
		if(!valRes.isSuccess()){
			res.setSuccess(false);
			res.setMessage(valRes.getMessage());
			return res;
		}
		
		//查出点评内容
		UserComment condi=new UserComment();
		condi.setUserId(user.getId());
		condi.setForeignId(user.getClassId());
		condi.setType(UserCommentEnums.type._class.getValue());
		List<UserLessonCommentDTO> commList=userCommentService.findUserComment(condi);
		if(commList.size()>0){
			res.setSuccess(false);
			res.setMessage(UserLessonProMess.ERR_EDN_HAS);
			return res;
		}		
		String content=reqBehavior.getEnd().getContent();
		Integer star=reqBehavior.getEnd().getStar();	
		UserComment record=new UserComment();
		record.setForeignId(user.getClassId());
		record.setUserId(user.getId());
		record.setContent(content);
		record.setStar(star);
		record.setLevel(1);
		record.setVerifyStatus(UserCommentEnums.verifyStatus.fail.getValue());
		record.setType(UserCommentEnums.type._class.getValue());
		userCommentService.addUserComment(record);
		
		return ResBoolSimpleInfo.getSuccessInfo();
	}
	

	/**
	 * 构建结果页
	 */
	@Override
	public void genEnd(List<UserLessonTreeDTO> res,String userId){
		//构建结果页链接
		User user=userService.selectByPrimaryKey(userId);		
		String endSta=StringUtils.EMPTY;
		String endLeafSta=StringUtils.EMPTY;
		if(user.getLearnStatus().equals(UserEnums.learnStatus.trainning.getValue())){
			endSta=UserLessonProgressEnums.status.lock.getValue();
			endLeafSta=UserLessonProgressEnums.status.lock.getValue();
		}else{
			endSta=UserLessonProgressEnums.status.finish.getValue();
			endLeafSta=UserLessonProgressEnums.status.studying.getValue();
		}	
		UserLessonTreeDTO last2=genEndObj(endSta);
		res.add(last2);
		UserLessonTreeDTO last1=genEndLeafObj(endLeafSta);
		res.add(last1);
	}
	
	@Override
	public UserLessonTreeDTO genEndObj(String endUserLesSta){
		UserLessonTreeDTO last2=new UserLessonTreeDTO();
		last2.setIsLeaf(CommEnums.isLeaf.no.getValue());
		last2.setId(UserLessonProgressCons.END_LESSON_ID2);
		last2.setLevel(1);
		last2.setName(LessonCons.END);
		last2.setResourceType("");
		last2.setUserLesSta(endUserLesSta);
		return last2;
	}
	
	@Override
	public UserLessonTreeDTO genEndLeafObj(String endUserLesSta){
		UserLessonTreeDTO last1=new UserLessonTreeDTO();
		last1.setIsLeaf(CommEnums.isLeaf.yes.getValue());
		last1.setId(UserLessonProgressCons.END_LESSON_ID1);
		last1.setLevel(2);
		last1.setParentId("2");
		last1.setName(LessonCons.END_LEAF);
		last1.setResourceType("");
		last1.setUserLesSta(endUserLesSta);
		return last1;
	}
	
	
	
	
	
	/**
	 * 结果页
	 * @throws Exception 
	 */
	@Override
	public void chooseEnd(RespGetLessonContent respOpenLessonContent,User user,String lessonId) throws Exception{
		
		if(lessonId.equals(UserLessonProgressCons.END_LESSON_ID1) && !user.getLearnStatus().equals(UserEnums.learnStatus.trainning.getValue())){
			//结果页面	
			RespGetLessonEnding respGetLessonEnding=new RespGetLessonEnding();
			//待考核
			if(user.getLearnStatus().equals(UserEnums.learnStatus.waiting.getValue())){
				//查出点评内容
				UserComment condi=new UserComment();
				condi.setUserId(user.getId());
				condi.setForeignId(user.getClassId());
				condi.setType(UserCommentEnums.type._class.getValue());
				List<UserLessonCommentDTO> commList=userCommentService.findUserComment(condi);
				if(commList.size()>0){
					respGetLessonEnding.setContent(commList.get(0).getContent());
					respGetLessonEnding.setStar(commList.get(0).getStar());
					respGetLessonEnding.setCommCreateTime(commList.get(0).getCreateTime());
					respGetLessonEnding.setEndStatus(UserLessonProgressEnums.endingStatus.commented.getValue());	
				}else{
					respGetLessonEnding.setEndStatus(UserLessonProgressEnums.endingStatus.commenting.getValue());	
				}							
			}else{			
				if(user.getLearnStatus().equals(UserEnums.learnStatus.graduation.getValue())){
					//通过
					respGetLessonEnding.setEndStatus(UserLessonProgressEnums.endingStatus.pass.getValue());	
					List<UserLessonProgress> listP=userLessonProgressService.findByUserAttr(user.getId(),user.getClassId(),LessonEnums.attr.check.getValue());				
					List<RespGetLessonEndingMark> markList=new ArrayList<RespGetLessonEndingMark>();
					for(UserLessonProgress ulp:listP){
						String markLessonId=ulp.getLessonId();
						Lesson lesson=lessonAPI.selectLessonById(markLessonId);	
						markList.add(new RespGetLessonEndingMark(lesson.getName(),ulp.getGetMark()));	
					}				
					respGetLessonEnding.setMarkList(markList);
					respGetLessonEnding.setMarkConfig(Double.valueOf(UserLessonProgressCons.END_MARK_PASS));
				}else{
					//不通过
					respGetLessonEnding.setEndStatus(UserLessonProgressEnums.endingStatus.fail.getValue());	
				}	
				
				LessonClassUserRelation rel=lessonAPI.selectLesClsUseRel(user.getClassId(), user.getId(), UserEnums.type.student.getValue());
				UserLessonProgress endPro=userLessonProgressService.selectUserEndLesson(user.getId(),user.getClassId(),UserLessonProgressCons.END_LESSON_ID1);				
				respGetLessonEnding.setGetMark(endPro.getGetMark());
				User teacher=userService.selectByPrimaryKey(user.getParentId());
				respGetLessonEnding.setTeacherHeadImg(teacher.getHeadImg());
				respGetLessonEnding.setTeacherName(teacher.getUsername());
				respGetLessonEnding.setEndWord(rel.getEndWord());	
				respGetLessonEnding.setMarkConfig(Double.valueOf(UserLessonProgressCons.END_MARK_PASS));
				

			}						
			respOpenLessonContent.setRespGetLessonEnding(respGetLessonEnding);
		}	
	}
	
	/**
	 * 选择资源
	 * @param respOpenLessonContent
	 * @param resourceDetailDTO
	 */
	@Override
	public void chooseResource(
			RespGetLessonContent respOpenLessonContent,
			ResourceDetailDTO resourceDetailDTO){
		RespGetLessonResource respOpenLessonResource=respOpenLessonContent.getResource();
		if(respOpenLessonResource==null){
			respOpenLessonResource=new RespGetLessonResource();
		}
		respOpenLessonResource.setCreateTime(resourceDetailDTO.getCreateTime());
		respOpenLessonResource.setDescribes(resourceDetailDTO.getDescribes());
		respOpenLessonResource.setId(resourceDetailDTO.getId());
		respOpenLessonResource.setName(resourceDetailDTO.getName());
		respOpenLessonResource.setRequirement(resourceDetailDTO.getRequirement());
		respOpenLessonResource.setResourceType(resourceDetailDTO.getResourceType());			
		respOpenLessonResource.setSource(resourceDetailDTO.getSource());
		respOpenLessonResource.setTaskContent(resourceDetailDTO.getTaskContent());	
		respOpenLessonContent.setResource(respOpenLessonResource);
	}
	
	/**
	 * 选择视频
	 * @param respOpenLessonContent
	 * @param resourceDetailDTO
	 * @param resourceType
	 * @param status
	 */
	@Override
	public void chooseVideo(
			RespGetLessonContent respOpenLessonContent,
			ResourceDetailDTO resourceDetailDTO,
			Rule rule,
			String status,
			String loginUserId){		
			RespGetLessonVideo video=respOpenLessonContent.getVideo();
			if(video==null){
				video=new RespGetLessonVideo();
			}
			video.setResourceIcon(resourceDetailDTO.getResourceIcon());
			video.setResourceImg(resourceDetailDTO.getResourceImg());
			video.setResourceSize(resourceDetailDTO.getResourceSize());
			video.setResourceUrl(resourceDetailDTO.getResourceUrl());
			video.setTime(resourceDetailDTO.getTime());	
			video.setDuration(rule.getDuration());
			Long num=userPraiseService.sumByForeignId(respOpenLessonContent.getLessonId(),"0");			
			video.setGood(num);
			
			List<RespGetLessonExamAns> ans=new ArrayList<RespGetLessonExamAns>();
			
			List<LessonResourceRuleFrame> frameList=lessonAPI.findFrameByLessonId(respOpenLessonContent.getLessonId());
			
			for(LessonResourceRuleFrame f:frameList){
				RespGetLessonExamAns examAns=new RespGetLessonExamAns();
				ResourceQuestion q=questionAPI.selectQuestionById(f.getResourceQuestionId());
				examAns.setAnswerConfig(q.getAnswerConfig());
				examAns.setBody(q.getBody());
				examAns.setItemId(f.getId());
//				examAns.setMyAns(myAns);
				examAns.setQuestionType(q.getQuestionType());
				JSONArray jsonArr=JSON.parseArray(q.getAnswer());
				examAns.setRightAns(jsonArr);
				ans.add(examAns);
				examAns.setSecond(f.getSecond());
				examAns.setSort(f.getSort());
			}
										
			video.setAnsDetail(ans);	
			
			UserPraise isMyGood=userPraiseService.selectUserPraise(respOpenLessonContent.getLessonId(), loginUserId, CommEnums.resourceType.video.getValue(), UserPraiseEnums.isPraise.yes.getValue());
			video.setMyGood(isMyGood==null?false:true);
			
			respOpenLessonContent.setVideo(video);
	}
	
	/**
	 * 选择音乐
	 * @param respOpenLessonContent
	 * @param resourceDetailDTO
	 * @param resourceType
	 * @param status
	 */
	@Override
	public void chooseMusic(
			RespGetLessonContent respOpenLessonContent,
			ResourceDetailDTO resourceDetailDTO,
			String status){}
	
	/**
	 * 选择文件
	 * @param respOpenLessonContent
	 * @param resourceDetailDTO
	 * @param resourceType
	 * @param status
	 */
	@Override
	public void chooseFile(
			RespGetLessonContent respOpenLessonContent,
			ResourceDetailDTO resourceDetailDTO,
			String status){
	}
	
	/**
	 * 选择试卷
	 * @param respOpenLessonContent
	 * @param resourceDetailDTO
	 * @param resourceType
	 * @param status
	 */
	@Override
	public void chooseExam(
			UserLessonProgress currProgress,
			RespGetLessonContent respOpenLessonContent,
			ResourceDetailDTO resourceDetailDTO,
			String status){
			 String result=currProgress.getResult();
			 RespGetLessonExam resultExam=JSON.parseObject(result, RespGetLessonExam.class);
			 if(resultExam==null){
				 resultExam=new RespGetLessonExam();
			 } 
			 if(status.equals(UserLessonProgressEnums.status.studying.getValue())){
				 genExam(resultExam,resourceDetailDTO,true,false);
			 }
			 else if(status.equals(UserLessonProgressEnums.status.Auditing.getValue())){				 
				 if(currProgress.getOperNum()<UserLessonProgressCons.EXAM_MAX_TIME_TIPS){
					 //隐藏答案
					 genExam(resultExam,resourceDetailDTO,false,false);
					 resultExam.setAnsSimple(null);	
					 resultExam.setAnsDetail(null);
				 }
			 }
			 else if(status.equals(UserLessonProgressEnums.status.finish.getValue())){
				 //完成返回题目详细内容
				 genExam(resultExam,resourceDetailDTO,false,true);
			 }
			respOpenLessonContent.setExam(resultExam);		 
	}
	
	/**
	 * 构建试卷
	 * @param resultExam
	 * @param resourceDetailDTO
	 * @param _new 是否从资源读取
	 * @param showRight 是否显示答案
	 */
	private void genExam(
			RespGetLessonExam resultExam,
			ResourceDetailDTO resourceDetailDTO,
			Boolean _new,
			boolean showRight
			){	
			if(_new){
				 List<RespGetLessonExamAns> questionList=new ArrayList<RespGetLessonExamAns>();						 
				 List<ResourceExamItem> itemList=examAPI.findItemByExamId(resourceDetailDTO.getResourceExamId());
				 ResourceExam resourceExam=examAPI.selectExamById(resourceDetailDTO.getResourceExamId());
				 for(ResourceExamItem itme:itemList){
					 ResourceQuestion q=questionAPI.selectQuestionById(itme.getResourceQuestionId());						 
					 RespGetLessonExamAns respp=new RespGetLessonExamAns();
					 respp.setAnswerConfig(q.getAnswerConfig());
					 respp.setBody(q.getBody());
					 respp.setQuestionType(q.getQuestionType());
					 respp.setItemId(itme.getId());
					 if(showRight){
							JSONArray jsonArr=JSON.parseArray(q.getAnswer());
							respp.setRightAns(jsonArr);
					 }

					 questionList.add(respp);
				 }
				 //首次打开返回试卷题目详细内容
				 resultExam.setAnsDetail(questionList);
				 resultExam.setScore(resourceExam.getScore());
				 resultExam.setNum(resourceExam.getNum());
				 resultExam.setSeconds(resourceExam.getSeconds());
				 resultExam.setExamName(resourceExam.getName());
			}


	}
	
	
	/**
	 * 选择感想
	 * @param respOpenLessonContent
	 * @param resourceDetailDTO
	 * @param userId
	 * @param resourceType
	 * @param status
	 */
	@Override
	public void chooseThought(
			RespGetLessonContent respOpenLessonContent,
			String userId,
			String foreignId,
			String status){
		
		 		 RespGetLessonThought respOpenLessonThought=new RespGetLessonThought();	
		 		UserThoughts userThoughts=null;
		 		 if(!StringUtils.isEmpty(foreignId)){
		 			userThoughts=userThoughtsService.selectByPrimaryKey(foreignId);					 					 
		 		 }else{
					 userThoughts=userThoughtsService.selectUserThoughts(userId,respOpenLessonContent.getLessonId());	 					 
		 		 } 
				 if(userThoughts!=null){
					 respOpenLessonThought.setId(userThoughts.getId());
					 respOpenLessonThought.setLearnContent(userThoughts.getLearnContent());
					 respOpenLessonThought.setPlanContent(userThoughts.getPlanContent());
					 respOpenLessonThought.setThinkContent(userThoughts.getThinkContent());
					 respOpenLessonThought.setTitle(userThoughts.getTitle());	
					 respOpenLessonThought.setCreateTime(userThoughts.getCreateTime());
					 
					 //个人信息
					 RespGetLessonUserInfo userInfo=new RespGetLessonUserInfo();
					 User user=userService.selectByPrimaryKey(userThoughts.getUserId());
					 DefindBeanUtils.copyProperties(user, userInfo);
					 List<String> tags=userDataConfigService.findDataNameByUserIdAndType(userThoughts.getUserId(), UserEnums.userDataConfigType.tag.getValue());
					 userInfo.setTags(tags);
					 respOpenLessonThought.setUserInfo(userInfo);
					 
					 userLookService.addLook(userThoughts.getId(), CommEnums.resourceType.thought.getValue());
					 
				 }		 	
			 respOpenLessonContent.setThought(respOpenLessonThought);
			 
	}
	
	/**
	 * 选择评论作业
	 * @param userLessonProgress
	 * @param respOpenLessonContent
	 * @param resourceDetailDTO
	 * @param userId
	 * @param status
	 */
	@Override
	public void chooseHwNeedComment(
			UserLessonProgress userLessonProgress,
			RespGetLessonContent respOpenLessonContent,
			Rule rule,
			String userId,
			String loginUserId,
			String foreignId,
			String status){
			//评论作业无论课程内容有没改变，按照用户历史记录
			 RespGetLessonHwComment res=new RespGetLessonHwComment();
			 List<String> goodList=new ArrayList<String>();
			 List<String> badList=new ArrayList<String>();				 
			 if((rule.getNeedScore()!=null&&rule.getNeedScore()>=0)){
				 res.setNeedTeacher(true);
			 }else{
				 res.setNeedTeacher(false);
			 }
			 
			 	if(status.equals(UserLessonProgressEnums.status.studying.getValue())){
					//学习中，包含1.首次进入，2.老师不通过
			 		
					if(!StringUtils.isEmpty(foreignId)){
						 UserHw openHw=userHwService.selectByPrimaryKey(foreignId);
						 getDetailHwNeedComment(res,loginUserId,openHw,goodList,badList);						 
						 respOpenLessonContent.setStatus(UserLessonProgressEnums.status.finish.getValue());						 
					}else{
				 		res.setGoodList(goodList);
				 		res.setBadList(badList);
				 		res.setStatus(StringUtils.EMPTY);;
				 		res.setFirst(true);
					}			 		
				}
				else if(status.equals(UserLessonProgressEnums.status.Auditing.getValue())){
					//待考核，待老师审核，作业状态（新建），自己的赞踩
					UserHw initHw=null;
					if(!StringUtils.isEmpty(foreignId)){
						initHw=userHwService.selectByPrimaryKey(foreignId);
					}else{
						initHw=userHwService.selectUserHwByStatus(userId,userLessonProgress.getLessonId(),UserHwEnums.hwStatus.init.getValue());
					}					 
					getDetailHwNeedComment(res,loginUserId,initHw,goodList,badList);

				}
				else if(status.equals(UserLessonProgressEnums.status.finish.getValue())){
					//已完成，老师审核通过，作业状态（通过），老师的赞踩
					UserHw passHw=null;
					if(!StringUtils.isEmpty(foreignId)){
						passHw=userHwService.selectByPrimaryKey(foreignId);
					}else{
						 passHw=userHwService.selectUserHwByStatus(userId,userLessonProgress.getLessonId(),UserHwEnums.hwStatus.pass.getValue());
					}										
					getDetailHwNeedComment(res,loginUserId,passHw,goodList,badList);					 

				}
			 respOpenLessonContent.setHwNeedComment(res);
	}
	
	private void getDetailHwNeedComment(RespGetLessonHwComment res,String loginUserId,UserHw openHw,List<String> goodList,List<String> badList){
		 res.setUserFileUrl(openHw.getUserAttachUrl());
		 res.setUserFileName(openHw.getUserAttachName());
		 res.setFileSourceName(openHw.getFileSourceName());		
		 
		 if(openHw.getStatus().equals(UserHwEnums.hwStatus.init.getValue())){
			 goodList=userHwPraiseService.findUserHwPraiseStr(openHw.getId(), UserHwEnums.hwType.student.getValue(), UserHwEnums.HwPraiseType.praise.getValue());				 
			 res.setGoodList(goodList);			 				 
			 badList=userHwPraiseService.findUserHwPraiseStr(openHw.getId(), UserHwEnums.hwType.student.getValue(), UserHwEnums.HwPraiseType.tread.getValue());				 
			 res.setBadList(badList); 
		 }else{
			 goodList=userHwPraiseService.findUserHwPraiseStr(openHw.getId(), UserHwEnums.hwType.teacher.getValue(), UserHwEnums.HwPraiseType.praise.getValue());				 
			 res.setGoodList(goodList);			 				 
			 badList=userHwPraiseService.findUserHwPraiseStr(openHw.getId(), UserHwEnums.hwType.teacher.getValue(), UserHwEnums.HwPraiseType.tread.getValue());				 
			 res.setBadList(badList);
		 }
		 

		 
		 //总共多少赞
		 Long goodNum =userPraiseService.sumByForeignId(openHw.getId(),UserPraiseEnums.isPraise.yes.getValue());
		 res.setGood(goodNum==null?0:goodNum);
		 
		UserPraise isMyGood=userPraiseService.selectUserPraise(openHw.getId(), loginUserId, CommEnums.resourceType.hwNeedComment.getValue(), UserPraiseEnums.isPraise.yes.getValue());
		res.setIsMyGood(isMyGood==null?false:true);
		 
		 //个人信息
		 RespGetLessonUserInfo userInfo=new RespGetLessonUserInfo();
		 genUserInfo(userInfo,openHw);
		 res.setUserInfo(userInfo);
		 //作业信息
		 res.setId(openHw.getId());
		 res.setScore(openHw.getScore());
		 res.setUserId(openHw.getUserId());
		 res.setStatus(openHw.getStatus());
		 
		 //老师信息
		 User user=userService.selectByPrimaryKey(openHw.getUserId());
		 UserHwTeacher teaHw=userHwTeacherService.selectByHwAndUserId(openHw.getId(), user.getParentId());
		 if(teaHw !=null){
			 RespGetLessonTeacher teacher=new RespGetLessonTeacher();
			 genTeacher(teacher,user,openHw,teaHw);	
			 res.setTeacher(teacher); 
		 }	 
		 res.setFirst(false);
	}
	
	
	
	
	/**
	 * 选择提交作业
	 * @param userLessonProgress
	 * @param respOpenLessonContent
	 * @param resourceDetailDTO
	 * @param userId
	 * @param status
	 */
	@Override
	public void chooseHwJustCommit(	
			UserLessonProgress userLessonProgress,
			RespGetLessonContent respOpenLessonContent,
			Rule rule,
			String userId,
			String loginUserId,
			String foreignId,
			String status){
			//提交作业无论课程内容有没改变，按照用户历史记录
			 RespGetLessonHwCommit res=respOpenLessonContent.getHwJustCommit();
			 res=new RespGetLessonHwCommit();
			 if((rule.getNeedScore()!=null&&rule.getNeedScore()>=0)){
				 res.setNeedTeacher(true);
			 }else{
				 res.setNeedTeacher(false);
			 }
				if(status.equals(UserLessonProgressEnums.status.studying.getValue())){
					//学习中，包含1.首次进入，2.老师不通过，重新打开新页面
					if(!StringUtils.isEmpty(foreignId)){
						UserHw openHw=userHwService.selectByPrimaryKey(foreignId);
						 //待考核，待老师审核，作业状态（新建），
						getDetailHwJustCommit( res, loginUserId, openHw);
					}else{
						 res.setStatus(StringUtils.EMPTY);
						 res.setFirst(true);
					}
				}
				else if(status.equals(UserLessonProgressEnums.status.Auditing.getValue())){
					UserHw initHw=null;
					if(!StringUtils.isEmpty(foreignId)){
						initHw=userHwService.selectByPrimaryKey(foreignId);
					}else{
						initHw=userHwService.selectUserHwByStatus(userId,userLessonProgress.getLessonId(),UserHwEnums.hwStatus.init.getValue());
					}
					getDetailHwJustCommit( res, loginUserId, initHw);
				}
				else if(status.equals(UserLessonProgressEnums.status.finish.getValue())){
					//已完成，老师审核通过，作业状态（通过），老师的赞踩
					UserHw passHw=null;
					if(!StringUtils.isEmpty(foreignId)){
						 passHw=userHwService.selectByPrimaryKey(foreignId);
					}else{
						 passHw=userHwService.selectUserHwByStatus(userId,userLessonProgress.getLessonId(),UserHwEnums.hwStatus.pass.getValue());
					}					
					getDetailHwJustCommit( res, loginUserId, passHw);					 
				}		
				respOpenLessonContent.setHwJustCommit(res);		
				
	}
	
	private void getDetailHwJustCommit(RespGetLessonHwCommit res,String loginUserId,UserHw openHw){
		 res.setUserFileUrl(openHw.getUserAttachUrl());
		 res.setUserFileName(openHw.getUserAttachName());	
		 res.setFileSourceName(openHw.getFileSourceName());
		 
		 //个人信息
		 RespGetLessonUserInfo userInfo=new RespGetLessonUserInfo();
		 genUserInfo(userInfo,openHw);
		 res.setUserInfo(userInfo);
		 
		 //总共多少赞
		Long goodNum =userPraiseService.sumByForeignId(openHw.getId(),UserPraiseEnums.isPraise.yes.getValue());
		res.setGood(goodNum==null?0:goodNum);
		 
		UserPraise isMyGood=userPraiseService.selectUserPraise(openHw.getId(), loginUserId, CommEnums.resourceType.hwJustCommit.getValue(), UserPraiseEnums.isPraise.yes.getValue());
		res.setIsMyGood(isMyGood==null?false:true);
		 
		 //作业信息
		 res.setId(openHw.getId());
		 res.setScore(openHw.getScore());
		 res.setUserId(openHw.getUserId());
		 res.setStatus(openHw.getStatus());
		 
		 //老师信息
		 User user=userService.selectByPrimaryKey(openHw.getUserId());
		 UserHwTeacher teaHw=userHwTeacherService.selectByHwAndUserId(openHw.getId(), user.getParentId());
		 if(teaHw !=null){
			 RespGetLessonTeacher teacher=new RespGetLessonTeacher();
			 genTeacher(teacher,user,openHw,teaHw);	
			 res.setTeacher(teacher); 
		 }	
		 
		 res.setFirst(false);
	}
	
	
	private void genUserInfo(RespGetLessonUserInfo userInfo,UserHw passHw){
		 User user=userService.selectByPrimaryKey(passHw.getUserId());
		 DefindBeanUtils.copyProperties(user, userInfo);
		 List<String> tags=userDataConfigService.findDataNameByUserIdAndType(passHw.getUserId(), UserEnums.userDataConfigType.tag.getValue());
		 userInfo.setTags(tags);
		
	}
	
	private void genTeacher(RespGetLessonTeacher teacher,User user,UserHw passHw,UserHwTeacher teaHw){
		 User teacherInfo=userService.selectByPrimaryKey(user.getParentId());
		 teacher.setScore(passHw.getScore());
		 teacher.setContent(teaHw.getContent());
		 teacher.setCreateTime(teaHw.getCreateTime());
		 teacher.setHeadImg(teacherInfo.getHeadImg());
		 teacher.setUsername(teacherInfo.getUsername());
		 teacher.setTeachAttachName(teaHw.getTeachAttachName());
		 teacher.setTeachAttachUrl(teaHw.getTeachAttachUrl());
	}




	
	

}